package com.mifengs.mall.ui.main;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.util.ToIntentUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity {

    @BindView(R.id.et_input)
    EditText mEtInput;
    @BindView(R.id.iv_delete)
    ImageButton mIvDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, Color.WHITE);
        StatusBarUtils.StatusBarLightMode(this);
        init();
    }

    private void init() {
        mEtInput.addTextChangedListener(watcher);
        mEtInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search();
                    return true;
                }
                return false;
            }
        });
    }


    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s.toString())) {
                mIvDelete.setVisibility(View.INVISIBLE);
            } else {
                mIvDelete.setVisibility(View.VISIBLE);
            }
        }
    };

    @OnClick({R.id.ll_back, R.id.ll_search, R.id.iv_delete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.ll_search:
                search();
                break;
            case R.id.iv_delete:
                mEtInput.setText("");
                break;
        }
    }

    private void search() {
        String keyWord = mEtInput.getText().toString();
        String search = PreferenceUtils.getSearchUrl(this);
        if(!TextUtils.isEmpty(search)){
            ToIntentUtil.toCommonIntent(search+keyWord,this);
            finish();
        }
    }

}
